import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';

@Injectable()
export class GuardGuard implements CanActivate {

  // 使用  Reflector 反射读取 SetMetaData的值 去做判断这边例子是从url 判断有没有admin权限
  constructor(private Reflector: Reflector) { }

  // 守卫要求实现函数  给定参数context执行上下文 要求返回布尔值
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const admin = this.Reflector.get<string[]>('role', context.getHandler())
    const request = context.switchToHttp().getRequest<Request>()
    console.log('guard role=>', admin)
    // 获取链接的query参数
    return admin?.includes(request.query.role as string)
  }
}
